const util = require('util')

const jwt = require('jsonwebtoken')

const errorTypes = require('../contants/error-types')

const { PUBLIC_KEY } = require('../app/config')

class AuthMiddleware {
	// 验证 token 的有效性
	async verifyAuth(ctx, next) {
		console.log('验证授权的middleware~')
		// 1.获取token
		const authorization = ctx.headers.authorization
		if (!authorization) {
			const error = new Error(errorTypes.UNAUTHORIZATION)
			return ctx.app.emit('error', error, ctx)
		}
		const token = authorization.replace('Bearer ', '')
		console.log('token----', token)

		// 2.验证token
		try {
			// 如果签名不对，这里会报错，走到catch分支
			let payload = await util.promisify(jwt.verify)(token, PUBLIC_KEY, {
				algorithms: ['RS256'],
			})
			console.log('通过token解析出来的payload---', payload)

			let { openId, nickName, avatarUrl, uid } = payload
			ctx.user = { openId, nickName, avatarUrl, uid }

			// console.log('ctx.user----', ctx.user)

			// 404 bug
			await next()
		} catch (err) {
			console.log('jwt err---', err)
			const error = new Error(errorTypes.UNAUTHORIZATION)
			return ctx.app.emit('error', error, ctx)
		}
	}
}

module.exports = new AuthMiddleware()
